package com.xinqi.common.openfeign.interceptor;

import com.xinqi.common.core.constant.SecurityConstants;
import com.xinqi.common.core.utils.IpUtils;
import com.xinqi.common.core.utils.ServletUtils;
import com.xinqi.common.core.utils.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * feign 请求拦截器
 *
 * @author dgyu
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    public static final String SAME_TOKEN = "SA-SAME-TOKEN";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = ServletUtils.getRequest();
        if (request == null) {
            return;
        }
        Map<String, String> headers = ServletUtils.getHeaders(request);
        // 传递用户信息请求头，防止丢失
        String userId = headers.get(SecurityConstants.DETAILS_USER_ID);
        if (StringUtils.isNotEmpty(userId)) {
            requestTemplate.header(SecurityConstants.DETAILS_USER_ID, userId);
        }
        String userName = headers.get(SecurityConstants.DETAILS_USERNAME);
        if (StringUtils.isNotEmpty(userName)) {
            requestTemplate.header(SecurityConstants.DETAILS_USERNAME, userName);
        }
        String authentication = headers.get(SecurityConstants.AUTHORIZATION_HEADER);
        if (StringUtils.isNotEmpty(authentication)) {
            requestTemplate.header(SecurityConstants.AUTHORIZATION_HEADER, authentication);
        }
        // 同源请求
        String sameToken = headers.get(SAME_TOKEN);
        if (StringUtils.isNotEmpty(sameToken)) {
            requestTemplate.header(SAME_TOKEN, sameToken);
        }
        // 配置客户端IP
        requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr(ServletUtils.getRequest()));
    }
}
